import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
// 引入深拷贝方法
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'
// 引入路由
import { constantRoute, asyncRoutes, anyRoutes } from '@/router/routes'
// 引入数据类型
import {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
import { ElMessage } from 'element-plus'
import router from '@/router'
// 用于过滤异步路由,浅拷贝会有问题，因此需要使用深拷贝
function filterAsyncRoute(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      // 过滤子路由
      if (item.children && item.children.length) {
        // 重新赋值
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: localStorage.getItem('token') || '',
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组
      userName: '',
      avatar: '',
      buttons: []
    }
  },
  actions: {
    // 用户登录的方法
    async userLogin(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data)
      console.log(res, 222);
      if (res.code === 200) {
        // 存储token
        this.token = res.data
        localStorage.setItem('token', res.data)
        // 保证async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    // 获取用户信息
    async getUserInfo() {
      const res: userInfoResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.userName = res.data.name
        this.avatar = res.data.avatar
        this.buttons=res.data.buttons
        // 计算当前用户的路由        // 对比用户权限数组和异步数组
        let userAsyncRoutes = filterAsyncRoute(cloneDeep(asyncRoutes), res.data.routes)
        // 合并菜单路由
        this.menuRoutes = [...constantRoute, ...userAsyncRoutes, ...anyRoutes];
        // 目前路由器管理的只有默认路由，在用户计算完动态路由后需要动态追加
        [...userAsyncRoutes, anyRoutes].forEach((route: any) => {
          // 动态添加路由
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    // 退出
    async logout() {
      const res: any = await reqLogout()
      if (res.code === 200) {
        this.token = ''
        this.userName = ''
        this.avatar = ''
        localStorage.removeItem('token')
        ElMessage.success('退出成功')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
})

// 对外暴露
export default useUserStore
